package com.itheima.interceptor;

import com.itheima.utils.JwtUtils;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

@Slf4j
@Component
public class MyInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //    filterChain.doFilter(servletRequest,servletResponse);放行方法，不能随便放行
        HttpServletRequest req = (HttpServletRequest) request;
        HttpServletResponse res = (HttpServletResponse) response;


        String token = request.getHeader("token");
        if (token == null) {
            log.info("如果没有令牌");
            response.setStatus(401);
            return false;
        }

//        上面一个登录直接放行，一个没有令牌，最后一种情况就是有令牌，继续验证令牌是否有效即可

//        解析失败会抛出异常，所以try catch
        try {
            JwtUtils.parseJWT(token);
//            解析成功，直接放行
            return true;
        } catch (Exception e) {
            log.info("令牌无效");
            response.setStatus(401);
            return false;
        }

//        log.info("放行后");这个代码位于return后，永远不会被执行
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        HandlerInterceptor.super.postHandle(request, response, handler, modelAndView);
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        HandlerInterceptor.super.afterCompletion(request, response, handler, ex);
    }
}
